/******************************************************************************/
//	DxAnim2D.h	-	ANIMATIONS!
//
//	Author:		Russell Klinkerman
//	Created:	01.17.2004
//
/******************************************************************************/

#include "DxImage.h"
#include "DxAnim2D.h"
#include "KlinkTimer.h"

void	CDxAnim2D::Set(CDxImage*	_pSourceImage, unsigned int _uiRows, unsigned int _uiColumns,
				unsigned int _uiStartIndex, unsigned int _uiFrameCount,
					unsigned int _uiFrequency, bool _bLoop)
{
	pSourceImage	= _pSourceImage;
	uiRows			= _uiRows;
	uiColumns		= _uiColumns;
	uiStartIndex	= uiCurrentFrame = _uiStartIndex;
	uiFrameCount	= _uiFrameCount;
	uiFrequency		= _uiFrequency;

	rSource.left	= 0;
	rSource.top		= 0;
	rSource.right	= pSourceImage->GetWidth()	/ _uiColumns;
	rSource.bottom	= pSourceImage->GetHeight()	/ _uiRows;

	// Set playing flag
	uiFlags |= ANIM_PLAYING;

	// Set looping flag
	(_bLoop) ?	uiFlags |= ANIM_LOOPING	: uiFlags &= ~ANIM_LOOPING;
}

void	CDxAnim2D::Update()
{
	static CKlinkTimer	frameTimer(uiFrequency);
	unsigned int	uiLastFrame		= uiStartIndex + uiFrameCount - 1;
	unsigned int	uiTileWidth		= pSourceImage->GetWidth()	/ uiColumns;
	unsigned int	uiTileHeight	= pSourceImage->GetHeight()	/ uiRows;

	if(!(uiFlags & ANIM_PLAYING))
		return;

	// Check if it is time to change the frame.
	if(frameTimer.Check())
	{
		// Increment the frame.
		uiCurrentFrame++;

		// Check if animation is done playing.
		if(uiCurrentFrame > uiLastFrame)
		{
			if(uiFlags & ANIM_LOOPING)
			{
				// Reset the current frame to the first frame
				uiCurrentFrame = uiStartIndex;
			}
			else
			{
				uiFlags &= ~ANIM_PLAYING;		// Stop playing
				uiCurrentFrame = uiLastFrame;	// Reset to last frame (so something draws)
			}
		}

		// Set new source rectangle.
		rSource.left	= (uiCurrentFrame % uiColumns)	* uiTileWidth;
		rSource.top		= (uiCurrentFrame / uiColumns)	* uiTileHeight;
		rSource.right	= rSource.left	+ uiTileWidth;
		rSource.bottom	= rSource.top	+ uiTileHeight;

		// Reset frame timer
		frameTimer.Set(uiFrequency);
	}
}

void	CDxAnim2D::Draw(D3DXMATRIX	*	_pMatrix, bool _bSpriteDrawInProgress)
{
	// Begin sprite drawing
	if(!_bSpriteDrawInProgress)
		d3dManager.BeginSprites();
	
	// Draw animation frame
	d3dManager.Sprite( pSourceImage->GetTexture(), _pMatrix, -1, 0, &rSource );

	// End sprite drawing
	if(!_bSpriteDrawInProgress)
		d3dManager.EndSprites();
}
